package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时先别管事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Override
    public Travel get(String id) {
        Optional<Travel> optional = repository.findById(id);
        if (optional.isPresent()) {
            Travel travel = optional.get();
            //用户信息
            travel.setAuthor(userInfoService.get(travel.getUserId()));

            //目的地信息
            Destination dest = destinationService.get(travel.getDestId());
            travel.setDest(dest);
            return travel;
        }
        return null;
    }

    //page对象里面包括: 总页数 每页显示条数......
    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //出行时间
        TravelCondition day = qo.getDay();
        if (day != null) {
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lt(day.getMax()));
        }
        //游记消费
        TravelCondition perExpend = qo.getPerExpend();
        if (perExpend != null) {
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lt(perExpend.getMax()));
        }
        //最新排序
        int orderType = qo.getOrderType();
        if (orderType == 1) {
            Sort sort = Sort.by(Sort.Direction.DESC, "releaseTime");
            query.with(sort);
        }
        //最热排序
        if (orderType == 2) {
            Sort sort = Sort.by(Sort.Direction.DESC, "viewnum");
            query.with(sort);
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        Page<Travel> page = DBHelper.query(template, Travel.class, query, pageable);
        //页面确实用户对象
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }

    @Override
    public String saveOrUpdate(Travel travel, UserInfo user) {
        //目的地名称
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());
        //获取用户id并设置
        if (user != null) {
            travel.setUserId(user.getId());
        }
        //创建时间/最后更新时间
        travel.setLastUpdateTime(new Date());
        if (!StringUtils.hasLength(travel.getId())) {
            travel.setId(null);
            //创建时间
            travel.setCreateTime(new Date());

            repository.save(travel);
        } else {
            //更新
            //方案1: 1:查询  2: 替代  3:save
            //方案2: 显示使用update逻辑 update set...
            //条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));

            DBHelper.update(template, query, travel,
                    "destId", "destName", "title",
                    "coverUrl", "travelTime", "perExpend",
                    "day", "person", "lastUpdateTime",
                    "isPublic", "state", "summary", "content");
        }

        return travel.getId();
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void changeState(String id, int state) {
        //1:满足什么条件才进行审核
        Optional<Travel> op = repository.findById(id);
        if (!op.isPresent() && state != Travel.STATE_WAITING) {
            throw new LogicException("参数异常");
        }
        Travel travel = new Travel();
        travel.setId(id);
        travel.setLastUpdateTime(new Date());
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        if (state == Travel.STATE_RELEASE) {
            //2:审核通过要做什么
            //发布时间  最后更新时间  state
            travel.setState(Travel.STATE_RELEASE);  //通过
            travel.setReleaseTime(new Date());
        } else {
            //3:审核拒绝要做什么
            //发布时间  最后更新时间  state
            travel.setState(Travel.STATE_REJECT);  //拒绝
            travel.setReleaseTime(null);
        }
        DBHelper.update(template, query, travel, "state", "lastUpdateTime", "releaseTime");
    }

    @Override
    public List<Travel> getViewnumTop3(String destId) {
        //点击量前3
        Pageable of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> list = repository.findByDestId(destId, of);
        return list;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public List<Travel> findByDestName(String destName) {
        List<Travel> list = repository.findByDestName(destName);
        for (Travel travel : list) {
            //用户信息
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return list;
    }

    @Override
    public void audit(String id, int state) {
        Travel travel = this.get(id);
        if (travel == null) {
            throw new LogicException("参数异常");
        }
        if (travel.getState() != Travel.STATE_WAITING) {
            throw new LogicException("不是待审核状态，不允许审核");
        }
        if (state == Travel.STATE_RELEASE) {
            //审核通过之后需要做什么
            //修改状态为通过状态
            travel.setState(Travel.STATE_RELEASE);
            //修改发布时间
            travel.setReleaseTime(new Date());
            //最后更新时间
            travel.setLastUpdateTime(new Date());
            //记录审核信息（审核人，审核时间，审核状态，审核备注）
            this.saveOrUpdate(travel, null);
        } else if (state == Travel.STATE_REJECT) {
            //审核拒绝之后需要做什么
            travel.setState(Travel.STATE_REJECT);
            //修改发布时间
            travel.setReleaseTime(null);
            //最后更新时间
            travel.setLastUpdateTime(new Date());
            //记录审核信息（审核人，审核时间，审核状态，审核备注）
            this.saveOrUpdate(travel, null);
        } else {
            throw new LogicException("状态异常");
        }
    }

    @Override
    public List<Travel> queryByDestName(String keyword) {
        List<Travel> travels = repository.findByDestName(keyword);
        if (travels.size()!=0){
            for (Travel travel:travels){
                travel.setAuthor(userInfoService.get(travel.getUserId()));
            }
        }
        return travels;
    }


}
